<template>
  <div>
    <div class="mu_box">
      <el-form
        class="multiple_form"
        label-position="top"
        :model="form"
        ref="formName"
        :rules="rules"
        :inline="false"
        size="normal"
      >
        <el-form-item label="应用程序名称csv" prop="siddhiAppName">
          <el-select
            class="w100"
            size="small"
            filterable
            v-model="form.siddhiAppName"
            placeholder="请选择"
          >
            <el-option
              v-for="item in listSiddhiApps"
              :key="item.siddhiAppName"
              :label="item.siddhiAppName"
              :value="item.siddhiAppName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="form.siddhiAppName">
          <el-form-item label="流名称" prop="streamName">
            <el-select
              class="w100"
              size="small"
              placeholder="请选择一个流"
              filterable
              v-model="form.streamName"
              @change="streamSele"
            >
              <el-option
                v-for="item in form.listStreams"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="CSV文件" prop="fileName">
            <el-select
              class="w100"
              size="small"
              placeholder="请选择"
              filterable
              v-model="form.fileName"
            >
              <el-option
                v-for="item in filesList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-upload
            style="margin-top: 10px"
            class="upload-demo"
            action="/simulation/files"
            :file-list="fileList"
            :on-error="onError"
            :on-success="onSuccess"
            :limit="1"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">上 传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传CSV文件</div>
          </el-upload>

          <el-form-item label="分隔符" prop="delimiter">
            <el-input
              v-model="form.delimiter"
              placeholder=""
              size="small"
              clearable
            ></el-input>
          </el-form-item>
          <div class="senior_show_btn">
            <el-button size="small" @click="seniorShow = !seniorShow"
              >高级配置
              <i
                :class="seniorShow ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
              ></i>
            </el-button>
          </div>
          <el-collapse-transition>
            <div class="senior_option" v-show="seniorShow">
              <div class="user_paw">
                <el-form-item
                  class="w100"
                  style="margin-right: 10px"
                  label="CSV事件记录时间戳索引"
                  prop="timestampAttribute"
                >
                  <el-radio
                    slot="label"
                    v-model="form.isTimestampInterval"
                    :label="false"
                    >CSV事件记录时间戳索引</el-radio
                  >
                  <el-input
                    :disabled="form.isTimestampInterval"
                    v-model="form.timestampAttribute"
                    placeholder="请输入"
                    size="small"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item
                  class="w100"
                  label="事件时间递增为(ms)"
                  prop="timestampInterval"
                >
                  <el-radio
                    slot="label"
                    v-model="form.isTimestampInterval"
                    :label="true"
                    >事件时间递增为(ms)</el-radio
                  >
                  <el-input
                    :disabled="!form.isTimestampInterval"
                    v-model="form.timestampInterval"
                    placeholder="请输入"
                    size="small"
                    clearable
                  ></el-input>
                </el-form-item>
              </div>
              <el-form-item label="CSV文件按时间戳排序" prop="isOrdered">
                <el-radio v-model="form.isOrdered" :label="true">是</el-radio>
                <el-radio v-model="form.isOrdered" :label="false">否</el-radio>
              </el-form-item>
              <div v-if="form.listAttributes.length !== 0">
                <div style="color: #666666; font-size: 14px; margin-top: 20px">
                  列索引映射
                </div>
                <el-form-item
                  v-for="(li, index) in form.listAttributes"
                  :key="li.name"
                  :prop="'listAttributes.' + index + '.value'"
                  :rules="[
                    {
                      required: true,
                      trigger: 'blur',
                    },
                    {
                      validator(rule, value, callback) {
                        validatorForm(rule, value, callback);
                      },
                      trigger: 'blur',
                    },
                  ]"
                >
                  <span slot="label">{{ li.name }} ({{ li.type[0] }})</span>
                  <el-input
                    v-model="li.value"
                    placeholder="请输入"
                    size="small"
                    clearable
                  ></el-input>
                </el-form-item>
              </div>
            </div>
          </el-collapse-transition>
        </div>
      </el-form>
    </div>
    <div class="btns">
      <el-button size="small" v-if="isDel" @click="handleDel">删除</el-button>
      <el-button size="small" type="primary" @click="onSubmit">完成</el-button>
    </div>
  </div>
</template>

<script>
import Datepicker from "@/components/Datepicker";
import { mapGetters } from "vuex";
import _ from "lodash";
import { listStreams, listAttributes, getFiles } from "@/api/siddhi";

export default {
  components: {
    Datepicker,
  },
  computed: {
    validatorForm() {
      return function (rule, value, callback) {
        var reg = /^\d{1,}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("必须输入数字!!"));
        }
      };
    },
    ...mapGetters(["listSiddhiApps"]),
  },
  props: {
    AnalogSourceObj: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: null,
    },
  },
  watch: {
    // 应用程序下拉框选择或者赋值之后触发
    "form.siddhiAppName"(val) {
      if (val) {
        const obj = this.AnalogSourceObj.find(
          (i2) =>
            i2.siddhiAppName == val && i2.simulationType == "CSV_SIMULATION"
        );

        // 存在直接回显,不存在的 置空
        console.log(obj, "是否是编辑", this.AnalogSourceObj);
        if (obj) {
          this.isDel = true;
          // this.form.listAttributes = obj.listAttributes;
          // 找到的话深拷贝在赋值,不然下拉框会同步修改父节点属性
          this.form = _.cloneDeep(obj);
        } else {
          this.isDel = false;
          this.form.listAttributes = [];
          // this.form.streamName = "";
          this.$set(this.form, "streamName", "");
        }

        // this.form.listStreams = [];

        this.siddhiSele(val);
      }
    },
    "form.tableName"(val) {
      // this.retrieveTableNames()
      if (val) {
        this.changeTabName(val);
      }
    },
  },
  mounted() {
    this.getFiles();
  },
  data() {
    return {
      seniorShow: false,
      filesList: [],
      databaseMsg: "",
      btnLoading: false,
      rules: {
        siddhiAppName: [{ required: true, message: "请选择应用程序" }],
        streamName: [{ required: true, message: "请选择流" }],
        fileName: [{ required: true, message: "请选择CSV文件" }],
        delimiter: [{ required: true, message: "请输入分隔符" }],
      },
      isDel: false,
      fileList: [],
      form: {
        indices: "",
        isOrdered: false,
        isTimestampInterval: false,
        timestampAttribute: "",
        timestampInterval: "",
        siddhiAppName: "",
        streamName: "",
        listAttributes: [],
        simulationType: "CSV_SIMULATION", //类型===随机的 cvg 数据库
        fileName: "", //文件名称
        delimiter: ",", //分隔符
      },
    };
  },
  methods: {
    onSuccess(res) {
      this.getFiles();
      this.$msg({
        type: "success",
        message: "上传成功!",
      });
      this.fileList = [];
    },
    onError(err) {
      const msg = JSON.parse(err.message);
      if (msg.message) {
        this.$msg({
          type: "error",
          message: msg.message,
        });
      }
    },
    beforeAvatarUpload(file) {
      const isCSV = file.type === "text/csv";

      if (!isCSV) {
        this.$msg("上传文件只能是 csv 格式!");
      }

      return isCSV;
    },
    getFiles() {
      getFiles().then((res) => {
        this.filesList = res.data;
      });
    },
    // 添加流并获取流下的属性
    streamSele(val) {
      listAttributes({
        siddhiAppName: this.form.siddhiAppName,
        streamName: this.form.streamName,
      }).then((res) => {
        const { data } = res;

        this.form.listAttributes = data.map((item, index) => {
          return {
            ...item,
            isCheck: false,
            value: index,
            type: [item.type],
          };
        });
      });
    },
    // 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组，如不传则移除整个表单的校验结果
    clearValidate(fromName) {
      this.$nextTick(() => {
        this.$refs["formName"].clearValidate(fromName);
      });
    },
    // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
    resetFields() {
      this.$nextTick(() => {
        this.form = this.$options.data().form;
        this.$refs["formName"].resetFields();
      });
    },
    // 提交
    onSubmit() {
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          // this.form.columnNamesList = this.form.listAttributes.join(",");
          this.form.isTimestampInterval == true
            ? (this.form.timestampAttribute = "")
            : (this.form.timestampInterval = "");
          this.form.indices = this.form.listAttributes
            .map((item) => item.value)
            .join(",");
          this.form.attributeConfList = [_.cloneDeep(this.form)];

          this.$emit("onSubmit", this.form);
          this.resetFields();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除
    handleDel() {
      this.$emit("handleDelSiddhiType", this.form);
    },
    // 获取流
    siddhiSele(val) {
      listStreams(val).then((res) => {
        const { data } = res;

        this.$set(
          this.form,
          "listStreams",
          data.map((item) => {
            return {
              name: item,
            };
          })
        );
      });
    },
  },
};
</script>


<style scoped lang='scss'>
.senior_show_btn {
  display: flex;
  justify-content: flex-end;
}
.user_paw {
  display: flex;
  justify-content: space-between;
}
.display_flex {
  width: 100%;
  justify-content: space-between;
}
.btns {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  /* padding: 0 30px; */
  position: absolute;
  bottom: 30px;
  right: 20px;
  width: 100%;
}
.mu_box {
  height: calc(100vh - 160px);
  overflow: auto;
  border-bottom: 1px solid #e4e4e4;
  padding: 0 20px;
  padding-bottom: 30px;

  /deep/ .el-form-item {
    margin-bottom: 0;
    .el-form-item__label {
      padding: 0;
      width: 100% !important;
    }
  }
}
</style>